﻿using UnityEngine;
using System.Collections;

public class MoveTarget : MonoBehaviour
{

    private bool move;
    private bool isPortal;
    private GameObject destroyBean;
    private Vector3 portalPosition;
    private Obstacle obstacle;
    private float moveTime;
    private Vector3 startPosition;
    // Use this for initialization
    void Start ()
    {
        this.gameObject.GetComponent<Rigidbody> ().detectCollisions = false;
        move = false;
        destroyBean = null;
    }
    
    // Update is called once per frame
    void Update ()
    {
        if (move)
        {
            MovePlayer ();
        }
    }

    void OnTriggerEnter (Collider moveTarget)
    {
        if (moveTarget != null)
        {
            obstacle = moveTarget.gameObject.GetComponent<Obstacle> ();
            if (obstacle != null)
            {
                //碰到障碍物
                if (obstacle.obstacleType == ObstacleType.regular)
                {
                    move = false;
                    GameController.gameController.player.gameObject.GetComponent<Player> ().StopMove ();
                }

                //碰到传送门
                else if (obstacle.obstacleType == ObstacleType.portal)
                {
                    portalPosition = obstacle.gameObject.GetComponent<Portal> ().target.position;
                    isPortal = true;
                }

                //碰到豆子
                else if (obstacle.obstacleType == ObstacleType.bean)
                {
                    GameController.gameController.EatBean ();
                    destroyBean = moveTarget.gameObject;
                }

                //碰到大豆
                else if (obstacle.obstacleType == ObstacleType.bigBean)
                {
                    GameController.gameController.EatBigBean ();
                    destroyBean = moveTarget.gameObject;
                }
            }
        }

        //取消刚体碰撞
        this.gameObject.GetComponent<Rigidbody> ().detectCollisions = false;
    }

    //移动玩家
    private void MovePlayer ()
    {
        GameController.gameController.player.position = Vector3.Lerp (startPosition, this.transform.position, moveTime);
        if (moveTime >= 1)
        {
            move = false;
            GameController.gameController.player.gameObject.GetComponent<Player> ().StopMove ();

            if (!isPortal)
            {
                GameController.gameController.player.position = this.transform.position;
            }
            else
            {
                isPortal = false;
                GameController.gameController.player.position = portalPosition;
            }
            if (destroyBean != null)
            {
                Destroy (destroyBean);
            }
        }
        moveTime += Time.deltaTime * 4;
    }

    //初始化移动
    public void StartMove ()
    {
        move = true;
        moveTime = 0;
        startPosition = GameController.gameController.player.position;
    }

}
